package gw.com.android.ui.me;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.ui.BaseActivity;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;

/**
 * @author jett
 * @since 2018-03-05.
 */
public class NicknameActivity extends BaseActivity {

    public static final String NAME = "name";

    @BindView(R.id.nickname_edit)
    EditText etNickname;
    @BindView(R.id.nickname_clear)
    ImageView ivClear;
    @BindView(R.id.nickname_save)
    TextView tvSave;

    private String originalName;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_nickname;
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(R.string.profile_nickname_modify);
        etNickname.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
        etNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = etNickname.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    ivClear.setVisibility(View.GONE);
                    tvSave.setEnabled(false);
                } else {
                    ivClear.setVisibility(View.VISIBLE);
                    tvSave.setEnabled(text.length() >= 2);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etNickname.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    hideInput();
                    return true;
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    hideInput();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void initViewData() {
        originalName = getIntent().getStringExtra(NAME);
        if (!TextUtils.isEmpty(originalName)) {
            etNickname.setText(originalName);
            etNickname.setSelection(originalName.length());
        }
    }

    @OnClick(R.id.nickname_save)
    void save(View view) {
        String text = etNickname.getText().toString();
        if (!validateNickname(text)) {
            new ToastPopWindow(getApplicationContext(), getString(R.string.profile_nickname_out_regular)).show();
            return;
        }
        String num = PhoneNumber.getInstance().get();
        if (TextUtils.isEmpty(num)) {
            onModifyFailed(null);
            return;
        }
        if (text.equals(originalName)) {
            setResult(Activity.RESULT_CANCELED);
            finish();
            return;
        }
        showLoading();
        new ProfileRequest().modifyNickname(num, text, new HttpCallback<String>() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                onModifySuccess(result);
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(e);
                hideLoading();
                onModifyFailed(e);
            }
        });
    }

    private void onModifySuccess(String nickname) {
        new ToastPopWindow(getApplicationContext(), getString(R.string.profile_modify_success)).show();
        Intent result = new Intent();
        result.putExtra(NAME, nickname);
        setResult(RESULT_OK, result);
        finish();
    }

    private void onModifyFailed(Exception e) {
        if (e != null && "该昵称已被占用，请使用其他昵称！".equals(e.getMessage())) {
            new ToastPopWindow(getApplicationContext(), getString(R.string.profile_nickname_repeat)).show();
        } else {
            new ToastPopWindow(getApplicationContext(), getString(R.string.profile_nickname_modify_failed)).show();
        }
    }

    private boolean validateNickname(String text) {
        String regex = "^[0-9]+$";
        if (!text.matches(regex)) {
            regex = "[_a-zA-Z0-9\\u4e00-\\u9fa5]{2,10}";
            return text.matches(regex);
        }
        return false;
    }

    @OnClick(R.id.nickname_clear)
    void clear(View view) {
        etNickname.setText("");
    }

    private void hideInput() {
        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null) {
            im.hideSoftInputFromWindow(etNickname.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    protected void onDestroy() {
        hideInput();
        super.onDestroy();
    }
}
